// packageA/others/materialDetail/materialDetail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iPnoneBottomBol: false,
    imgPath: app.globalData.imgPath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.options = options;
    this.getiPnoneBottom();
    this.initData();
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  initData() {
    this.setData({
      posterShow: false,
      posterImg: '',
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      theme_color: basic_info.theme_color
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let json = {
      title: "",
      description: "",
      imgUrl: ""
    };
    json.title = this.data.info.title ? this.data.info.title : this.data.info.name;
    json.description = this.data.info.content ? this.data.info.content : this.data.info.name;
    json.imgUrl = this.data.info.images.length <= 0 ? this.data.info.set.icon : this.data.info.images[0];
    return {
      title: json.title,
      imageUrl: json.imgUrl,
      path: '/mircoApp/material/materialDetail/materialDetail?mid=' + mid + '&id=' + this.data.options.id
    }
  },
  onShareTimeline(){
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let json = {
      title: "",
      description: "",
      imgUrl: ""
    };
    json.title = this.data.info?.set.title ? this.data.info.set.title : this.data.info?.name;
    json.description = this.data.info?.set.desc ? this.data.info.set.desc : this.data.info?.name;
    json.imgUrl = this.data.info?.images.length <= 0 ? this.data.info.set.icon : this.data.info?.images[0];
    return {
      title: json.title,
      imageUrl: json.imgUrl,
      query: 'id=' + this.data.options.id +'&mid='+mid
    }
  },
  posterShowClose() {
    this.setData({
      posterShow: false
    });
  },
  saveImg() {
    // var times = _this.data.timeend - _this.data.timestart
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  getData() {
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.detail');
    app._getNetWork({
      url: urlStr,
      data: {
        id: this.data.options.id
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            info: res.data
          })
          console.log(this.data.info)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 海报生成
  postShow(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    if (!id) {
      wx.showToast({
        title: '该素材未设置关联商品',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (that.data.posterImg && this.data.posterId == id) {
      this.setData({
        posterShow: true
      });
    } else {
      this.data.posterId = id;
      wx.showLoading({
        title: '海报生成中',
      });
      let urlStr = app.getNetAddresss('goods.goods-poster.generate-goods-poster');
      app._getNetWork({
        url: urlStr,
        data: {
          id: id
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              posterShow: true,
              posterImg: res.data.image_url
            });
          } else {
            that.setData({
              posterShow: false
            });
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  download(e) {
    let images = e.currentTarget.dataset.images || [];
    let video = e.currentTarget.dataset.video || [];
    if (images.length > 0) {
      wx.showLoading({
        title: '正在下载图片...',
      })
      this.loadImg(images);
    }
    if (video && video.video_url) {
      wx.showLoading({
        title: '正在下载视频...',
      })
      this.loadVideo(video);
    }
  },
  loadImg(images) {
    images.forEach((item) => {
      wx.downloadFile({
        url: item, //需要下载的图片url
        success: function (res) { //成功后的回调函数
          wx.saveImageToPhotosAlbum({ //保存到本地
            filePath: res.tempFilePath,
            success(res) {
              wx.hideLoading();
              wx.showToast({
                title: '图片下载成功',
                icon: 'success',
                duration: 2000
              });
            },
            fail: function (err) {
              wx.hideLoading();
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata);
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。');
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                    }
                  }
                });
              }
            }
          });
        }
      });
    });
  },
  loadVideo(video) {
    wx.downloadFile({
      url: video.video_url, //需要下载的视频url
      success: function (res) { //成功后的回调函数
        wx.saveVideoToPhotosAlbum({ //保存到本地
          filePath: res.tempFilePath,
          success(res) {
            wx.hideLoading();
            wx.showToast({
              title: '视频下载成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveVideoToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata);
                  if (settingdata.authSetting['scope.saveVideoToPhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击视频保存到相册的提示。');
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                  }
                }
              });
            }
          }
        });
      }
    });
  },
  update(e) {
    let id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    wx.setClipboardData({
      data: title ? title : '',
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none',
          duration: 1500
        });
      },
      fail() {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 1500
        });
      }
    });
    this.setData({
      show1: true
    });

    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.updateNum');
    app._getNetWork({
      url: urlStr,
      data: {
        id: id,
        params: 'share'
      },
      success: function (resdata) {},
      fail: function (res) {
        console.log(res);
      }
    });
  },
  toGoods(e) {
    let good_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + good_id
    });
  }
})